package com.zx.designpattern.base;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.midcent.leakcanarylibrary.LeakCanaryManager;
import com.squareup.leakcanary.RefWatcher;
import com.zx.designpattern.view.activity.Interface4AllActivity;
import com.zx.designpattern.utils.interfaceforall.FunctionManager;
import com.zx.designpattern.presenter.BasePresenter;
import com.zx.designpattern.view.IBaseView;

import butterknife.ButterKnife;


/**
 * @作者 周翔
 * @创建时间 2018/2/3
 * @描述 Fragment基类
 * @修改时间 2018/2/3
 * @修改描述 Fragment基类
 * @修改者 周翔
 **/
public abstract class BaseFragment<V, T extends BasePresenter<V>> extends Fragment implements IBaseView {
    public String TAG = getClass().getName();
    FunctionManager mFunctionManager;// 万能接口管理器
    //表示层引用
    public T basePresenter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(getRootViewId(), null);
        ButterKnife.bind(this, mView);
        basePresenter = createPresenter();//新建presenter
        if (basePresenter != null)
            basePresenter.attachView((V) this);//attachview
        return mView;
    }

    protected abstract int getRootViewId();//fragment的layoutid

    public void setmFunctionManager(FunctionManager mFunctionManager) {
        this.mFunctionManager = mFunctionManager;
    }

    BaseActivity mBaseActivity;//只有集成BaseActivity的activity才能增加

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof Interface4AllActivity) {
            mBaseActivity = (BaseActivity) context;
            mBaseActivity.setFunctionForFragment(getTag());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (basePresenter != null)
            basePresenter.detachView();//detachView 防止内存泄漏


        //检测内存泄漏
        RefWatcher refWatcher = LeakCanaryManager.getInstance().getRefWatcher();
        refWatcher.watch(this);
    }

    protected abstract T createPresenter();

    @Override
    public void showLoading() {
        Toast.makeText(getContext(), "正在加载中。。。", Toast.LENGTH_LONG).show();

    }

    @Override
    public void hideLoading() {
        Toast.makeText(getContext(), "加载完毕。。。", Toast.LENGTH_LONG).show();

    }
}
